import { WXManager } from '../service/wx';
import { Auth } from '../middleware/auth';
import { AppUserModel } from '../model/app-user';
class AppUserDao {
  async codeToToken (code) {
    const openInfo = await WXManager.codeToUserIdAndKey(code);
    let user = await this.getUserByOpenid(openInfo.openid, openInfo.sessionKey);
    if (!user) {
      user = await this.registerByOpenid(openInfo.openid, openInfo.sessionKey);
    }
    console.log(Auth.USER);
    return Auth.generateToken(user.id, Auth.USER);
  }

  async getUserByOpenid (openid, sessionKey) {
    const user = await AppUserModel.findOne({
      where: {
        openid
      }
    });
    if (user && (user.session_key !== sessionKey)) {
      user.session_key = sessionKey;
      await user.save();
    }
    return user;
  }

  async registerByOpenid (openid, sessionKey) {
    const user = await AppUserModel.create({
      openid,
      session_key: sessionKey
    });
    return user;
  }
}

export { AppUserDao };
